<?php
if(session::user() && session::user()->id == '1')
{
   if($commit)
   {
      # UPDATE TYPES PROCEDURE
      $tc = in_array($_POST['f']['type'], array('a','c','f','g','b')) ? $_POST['f']['type'] : FALSE;

      if($tc != FALSE && is_array($_POST['f']['value']))
      {
         # SELECT ALL TYPES IN GIVEN KIND
         $DB->sql = 'SELECT * FROM `meccano_types` WHERE `type` = "' . $tc . '" ORDER BY `id`';
         $DB->DB_Fetch();
         $types = array();
         for($i=0, $t=$DB->rows; $i<$t; $i++)
         {
            $types[$DB->fetched[$i]['id']] = $DB->fetched[$i]['name'];
         }
         if(count($_POST['f']['value']) > 0)
         {
            # GET ID OF ALL TYPES STORED IN DB
            $typesId  = array_keys($types);
            $data2add = array();

            foreach($_POST['f']['value'] AS $key=>$value)
            {
               $key   = $FILTER->getFirstInteger($key);
               $value = mysql_real_escape_string($value);

               if(in_array($key, $typesId) && $value != $types[$key])
               {
                  # IF WE HAVE CHANGED VALUE OF EXIST TYPE - UPDATE THIS
                  $DB->sql = 'UPDATE `meccano_types` SET `name` = "' . $value . '" WHERE id = ' . $key . ' AND `type` = "' . $tc . '"';
                  $DB->DB_Query();
               } elseif(!in_array($key, $typesId) && $value != FALSE)
               {
                  # IF WE HAVE NO TYPE IN DB - ADD THIS
                  $data2add[] = '("' . $value . '", "' . $tc . '")';
               }
               unset($types[$key]); # UNSET TYPE FROM EXISTS TYPES - FOR DELETE WHATS LEFT
            }

            if(count($data2add) > 0)
            {
               # IF WE HAVE ANYTHING TO ADD - DO IT
               $DB->sql = 'INSERT INTO `meccano_types` (`name`, `type`) VALUES ' . implode(',', $data2add);
               $DB->DB_Query();
            }

            if(count($types) > 0)
            {
               # IF WE HAVE STORED TYPES WHICH ARE EPSENT IN _POST - DELETE THEM FROM DB
               $DB->sql = 'DELETE FROM `meccano_types` WHERE `id` IN (' . implode(',', array_keys($types)) . ') AND `system` = "0"';
               $DB->DB_Query();
            }
         }
      }
   }

   $DB->sql = 'SELECT * FROM `meccano_types` ORDER BY `type`, `id`';
   $DB->DB_Fetch();

   $SMARTY->assign('data', $DB->fetched);
   $layout = 'types.html';
} else
{
   if (session::user())
   {
      $ErrorHandler->setError(
              array(
                  'code' => 'access',
                  'varkey' => 'access_denied'
              )
      );
   }
   $layout = 'login.html';
}